// https://leetcode.cn/problems/second-minimum-node-in-a-binary-tree/
// Created by ade on 2022/8/11.
//
#include <iostream>
#include <vector>


using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<int> res;

    int findSecondMinimumValue(TreeNode *root) {
        dfs(root);
        sort(res.begin(), res.end());
        int k = unique(res.begin(), res.end()) - res.begin();
        if (k < 2) return -1;
        return res[1];
    }

    void dfs(TreeNode *node) {
        if (!node) return;
        res.push_back(node->val);
        dfs(node->left);
        dfs(node->right);
    }

    TreeNode *init() {
        TreeNode *h1 = new TreeNode(2);
        TreeNode *h2 = new TreeNode(2);
        TreeNode *h3 = new TreeNode(5);
        TreeNode *h4 = new TreeNode(5);
        TreeNode *h5 = new TreeNode(7);
        h1->left = h2;
        h2->left = h4;
        h1->right = h3;
        return h1;
    }
};

int main() {
    Solution so;
    TreeNode *h1 = so.init();
    cout << so.findSecondMinimumValue(h1) << endl;
    return 0;
}